package com.java1234.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.java1234.entity.Answer;
import com.java1234.entity.PageBean;
import com.java1234.entity.Question;
import com.java1234.entity.R;
import com.java1234.service.AnswerService;
import com.java1234.service.QuestionService;
import com.java1234.util.LogUtil;
import com.java1234.util.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 试题Controller
 */
@RestController
@RequestMapping("/bsns/subject/questions")
public class QuestionController {
    private static final Logger logger = LoggerFactory.getLogger(QuestionController.class);

    @Autowired private QuestionService questionService;

    @Autowired private AnswerService answerService;

    @Autowired private LogUtil logUtil;

    /**
     * 查询所有试题信息
     */
    @GetMapping("/listAll")
    public R listAll(){
        Map<String,Object> resultMap=new HashMap<>();
        resultMap.put("questions",questionService.list());
        return R.ok(resultMap);
    }

    /**
     * 分页查询试题信息
     * @param pageBean 分页信息
     */
    @PostMapping("/list")
    public R list(@RequestBody PageBean pageBean){
        String query = pageBean.getQuery().trim();
        QueryWrapper<Question> queryWrapper = new QueryWrapper<>();
        if (StringUtil.isNotEmpty(query)) {
            queryWrapper.like("title", query);
        }
        if (pageBean.getQuestionType() != null) {
            queryWrapper.eq("type", pageBean.getQuestionType());
        }
        if (pageBean.getQuestionBankId() != null) {
            queryWrapper.eq("bankid", pageBean.getQuestionBankId());
        }
        Page<Question> pageRes = questionService.page(new Page<>(pageBean.getPageNum(), pageBean.getPageSize()), queryWrapper);
        List<Question> questions = pageRes.getRecords();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("questions", questions);
        resultMap.put("total", pageRes.getTotal());
        return R.ok(resultMap);
    }

    /**
     * 根据ID查询试题信息
     * @param id 试题ID
     */
    @GetMapping("/{id}")
    public R getQuestionById(@PathVariable(value="id") Long id) {
        Question question = questionService.getById(id);
        if (question == null) {
            return R.error("没找到");
        }
        return R.ok().put("questions", question);
    }

    /**
     * 删除试题信息
     * @param ids 试题ID数组
     */
    @Transactional
    @PostMapping("/delete")
    public R delete(@RequestBody Long[] ids, HttpServletRequest request){
        for (Long id:ids){
            answerService.remove(new QueryWrapper<Answer>().eq("question_id",id));
        }
        questionService.removeByIds(Arrays.asList(ids));
        logger.info("删除成功");
        logUtil.logOperation(request, "根据ID删除试题信息", "POST /bsns/subject/questions/delete", Arrays.toString(ids), "成功");
        return R.ok("删除成功");
    }

    /**
     * 根据题库ID查询试题信息
     * @param type 试题类型
     */
    @GetMapping("/listByType")
    public R listByType(@RequestParam("type") int type) {
        List<Question> questions = questionService.list(new QueryWrapper<Question>().eq("type", type));
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("questions", questions);
        return R.ok(resultMap);
    }

    /**
     * 添加试题信息
     * @param question 试题对象
     */
    @PostMapping("/add")
    public R addQuestion(@Valid @RequestBody Question question, HttpServletRequest request){
        boolean isSaved=questionService.save(question);
        if(isSaved){
            logger.info("添加成功");
            logUtil.logOperation(request, "添加试题", "POST /bsns/subject/questions/add", question.toString(), "成功");
            return R.ok("添加成功");
        }else{
            logger.error("添加失败");
            logUtil.logOperation(request, "添加试题", "POST /bsns/subject/questions/add", question.toString(), "失败");
            return R.error("添加失败");
        }
    }

    /**
     * 查询试题最大ID
     */
    @GetMapping("/maxId")
    public R getMaxQuestionId() {
        Integer maxId = questionService.getMaxQuestionId();
        Map<String, Object> resultMap = new HashMap<>();
        resultMap.put("maxId", maxId);
        return R.ok(resultMap);
    }

    /**
     * 更新试题信息
     * @param question 试题对象
     */
    @PostMapping("/update")
    public R update(@RequestBody Question question, HttpServletRequest request) {
        {
            boolean isUpdated = questionService.updateById(question);
            if (isUpdated) {
                logger.info("修改成功");
                logUtil.logOperation(request, "更新试题信息", "POST /bsns/subject/questions/update", question.toString(), "成功");
                return R.ok("修改成功");
            } else {
                logger.error("修改失败");
                logUtil.logOperation(request, "更新试题信息", "POST /bsns/subject/questions/update", question.toString(), "失败");
                return R.error("修改失败");
            }
        }
    }
}
